package com.tang.mybatis;

import com.tang.mybatis.constants.Constants;
import com.tang.mybatis.mapping.MappedStatement;
import com.tang.mybatis.session.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;

/**
 * @author Tang
 * @classname XmlUtil
 * @description [  ]
 * @date 2022/4/6 23:04
 */
@Slf4j
public final class XmlUtil {

    /**
     * readMapperXml
     * @param fileName fileName
     * @param configuration configuration
     */
    public static void readMapperXml(File fileName, Configuration configuration) {
        SAXReader saxReader = new SAXReader();
        saxReader.setEncoding(Constants.CHARSET_UTF8);

        Document document = null;
        try {
            document = saxReader.read(fileName);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 获取xml中的根元素
        Element rootElement = document.getRootElement();

        if (Constants.XML_ROOT_LABEL.equals(rootElement.getName())) {
            log.error("mapper xml 文件根元素不是mapper!");
            return;
        }
        String namespace = rootElement.attributeValue(Constants.XML_SELECT_NAMESPACE);

        for (Iterator<Element> elementIterator = rootElement.elementIterator(); elementIterator.hasNext();) {
            Element element = elementIterator.next();
            String elementName = element.getName();

            MappedStatement mappedStatement = new MappedStatement();

            if (Constants.SqlType.SELECT.equals(elementName)) {
                String resultType = element.attributeValue(Constants.XML_SELECT_RESULT_TYPE);
                mappedStatement.setResultType(resultType);
                mappedStatement.setSqlType(Constants.SqlType.SELECT);
            } else if (Constants.SqlType.INSERT.equals(elementName)) {
                mappedStatement.setSqlType(Constants.SqlType.INSERT);
            } else if (Constants.SqlType.DELETE.equals(elementName)) {
                mappedStatement.setSqlType(Constants.SqlType.DELETE);
            } else if (Constants.SqlType.UPDATE.equals(elementName)) {
                mappedStatement.setSqlType(Constants.SqlType.UPDATE);
            } else {
                log.error("不支持的标签类型!");
                continue;
            }
            // 设置唯一的id
            String sqlId = namespace + "." + element.attributeValue("id");

            mappedStatement.setNamespace(namespace);
            mappedStatement.setSqlId(sqlId);
            mappedStatement.setSql(element.getStringValue().trim());

            System.out.println(mappedStatement);

            configuration.addMappedStatement(sqlId,mappedStatement);

        }

    }

}